/*
 * Copyright © 2018 www.noark.xyz All Rights Reserved.
 *
 * 感谢您选择Noark框架，希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ！
 * 除非符合Noark许可协议，否则不得使用该文件，您可以下载许可协议文件：
 *
 *        http://www.noark.xyz/LICENSE
 *
 * 1.未经许可，任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
 * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
 * 3.无论你对源代码做出任何修改和改进，版权都归Noark研发团队所有，我们保留所有权利;
 * 4.凡侵犯Noark版权等知识产权的，必依法追究其法律责任，特此郑重法律声明！
 */
package xyz.noark.network.rpc.shuttle;

import xyz.noark.core.annotation.Autowired;
import xyz.noark.core.exception.RpcTimeoutException;
import xyz.noark.network.rpc.RpcCallback;
import xyz.noark.network.rpc.RpcRouter;

import java.io.Serializable;
import java.util.Collection;

import static xyz.noark.log.LogHelper.logger;

/**
 * 基于Shuttle实现的Rpc消息路由器
 *
 * @author 小流氓[176543888@qq.com]
 * @since 4.0
 */
public class ShuttleRpcRouter implements RpcRouter {
    @Autowired
    private ShuttleConnectionManager connectionManager;

    public void setConnectionManager(ShuttleConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
    }

    @Override
    public void sendToClient(Serializable playerId, Serializable opcode, Object protocol) {
        // 给玩家发协议，就是向上一个节点转发，查找路由中上一个节点UID
        int serverUid = ShuttlePlayerManager.getPrevServerUid(playerId);
        ShuttleConnection connection = connectionManager.getConnection(serverUid);
        if (connection == null || !connection.isActive()) {
            logger.debug("给玩家发消息时上一跳连接不可用. playerId={}, opcode={}", playerId, opcode);
            return;
        }
        // 包装为Shuttle协议对象进行编码
        connection.send(new ShuttleRelayProtocol(playerId, opcode, protocol));
    }

    @Override
    public void broadcastToClient(Collection<Serializable> playerIdList, Serializable opcode, Object protocol) {
        // FIXME 过两天再来优化这个方法，要对上一个节点进行分组合并后再投递
        for (Serializable playerId : playerIdList) {
            this.sendToClient(playerId, opcode, protocol);
        }
    }

    @Override
    public <T> void asyncCall(int serverUid, Serializable opcode, Object protocol, Class<T> ackClass, RpcCallback<T> callback) {
        ShuttleConnection connection = connectionManager.getConnection(serverUid);
        if (connection == null) {
            throw new RpcTimeoutException("Could not get a connector from the pool. serverUid=" + serverUid);
        }
        if (!connection.isActive()) {
            throw new RpcTimeoutException("connector is not active. serverUid=" + serverUid);
        }
        connection.asyncCall(opcode, protocol, ackClass, callback);
    }

    @Override
    public <T> void asyncCall(int serverUid, Serializable opcode, Object protocol) {
        ShuttleConnection connection = connectionManager.getConnection(serverUid);
        if (connection == null) {
            throw new RpcTimeoutException("Could not get a connector from the pool. serverUid=" + serverUid);
        }
        if (!connection.isActive()) {
            throw new RpcTimeoutException("connector is not active. serverUid=" + serverUid);
        }
        connection.asyncCall(opcode, protocol);
    }

    @Override
    public <T> T syncCall(int serverUid, Serializable opcode, Object protocol, Class<T> ackClass) {
        ShuttleConnection connection = connectionManager.getConnection(serverUid);
        if (connection == null) {
            throw new RpcTimeoutException("Could not get a connector from the pool. serverUid=" + serverUid);
        }
        if (!connection.isActive()) {
            throw new RpcTimeoutException("connector is not active. serverUid=" + serverUid);
        }
        return connection.syncCall(opcode, protocol, ackClass);
    }
}